package com.shenjinzheng.movie_ticket_app.viewmodel


import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import androidx.lifecycle.viewModelScope
import com.shenjinzheng.movie_ticket_app.model.Movie
import com.shenjinzheng.movie_ticket_app.repository.MovieRepository
import kotlinx.coroutines.Dispatchers
import com.shenjinzheng.movie_ticket_app.utils.Result
import kotlinx.coroutines.launch


class MovieViewModel(private val movieRepository: MovieRepository) : ViewModel() {

    private var currentPage = 1
    private var isLoading = false
    private val _movies = MutableLiveData<List<Movie>>()
    val movies: LiveData<List<Movie>> get() = _movies

    fun loadMovies(apiKey: String) {
        viewModelScope.launch {
            val result = movieRepository.getPopularMovies(apiKey, currentPage)
            result.onSuccess { movieList ->
                if (currentPage == 1) {
                    _movies.value = movieList  // 第一页直接替换
                } else {
                    _movies.value = _movies.value?.plus(movieList)  // 后续页追加数据
                }
                currentPage++  // 增加页码
            }.onFailure {
                // 错误处理
            }
        }
    }

    fun searchMovies(apiKey: String, query: String) {
        viewModelScope.launch {
            val result = movieRepository.searchMovies(apiKey, query)
            result.onSuccess {
                _movies.value = it  // 更新电影列表
            }.onFailure {
                // 错误处理
            }
        }
    }
}
